package org.jason.common.satoken.service;

import cn.dev33.satoken.stp.StpInterface;
import org.jason.common.redis.RedisCache;
import org.jason.feign.user.UserClient;
import org.jason.model.common.dtos.ResponseResult;
import org.jason.model.user.pojos.CuRolePermission;
import org.jason.model.user.pojos.CuUserRole;
import org.jason.model.user.pojos.UserRolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 */
@Service
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserClient userClient;

    /**
     * @param userId    用户id
     * @param loginType 登录类型
     * @return 返回该用户具有的权限列表
     */
    @Override
    public List<String> getPermissionList(Object userId, String loginType) {
        UserRolePermission permission = getUserRolePermission(Integer.parseInt((String) userId));
        return permission.getPermissions().stream()
                .map(CuRolePermission::getPermission)
                .collect(Collectors.toList());
    }

    /**
     * @param userId    用户id
     * @param loginType 登录类型
     * @return 返回该用户具有的角色列表
     */
    @Override
    public List<String> getRoleList(Object userId, String loginType) {
        UserRolePermission permission = getUserRolePermission(Integer.parseInt((String) userId));
        return permission.getRoles().stream()
                .map(CuUserRole::getRoleName)
                .collect(Collectors.toList());
    }

    /**
     * 根据用户id返回用户权限表
     *
     * @param userId 用户id
     * @return 用户权限表
     */
    private UserRolePermission getUserRolePermission(Integer userId) {
        //先从redis中获取
        UserRolePermission permission = redisCache.getCacheObject("auth_" + userId);
        if (permission == null) {
            //从user服务获取
            ResponseResult<UserRolePermission> result = userClient.getUserRolePerm(userId);
            permission = result.getData();
        }
        return permission;
    }
}
